﻿using System;
using System.Runtime.Caching;

namespace DeHeng_Mes.Utils
{
    class CacheUtils {

        private static MemoryCache _cache = MemoryCache.Default;

        public static void AddToCache(string key, object value, DateTimeOffset? expirationTime = null) {
            if (expirationTime.HasValue) {
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = expirationTime.Value;
                _cache.Set(key, value, policy);
            } else {
                _cache.Set(key, value, null); // 使用默认缓存策略，不设置过期时间  
            }
        }

        public static object GetFromCache(string key) {
            return _cache.Get(key);
        }

        public static void RemoveFromCache(string key) {
            _cache.Remove(key);
        }

        public static void UpdateCacheExpiration(string key, DateTimeOffset newExpirationTime) {
            var cacheItem = _cache.GetCacheItem(key);

            if (cacheItem != null) {
                _cache.Remove(key);

                var value = cacheItem.Value; 
                _cache.Set(key, value, newExpirationTime);
            }
        }
    }

}
